<template>
	<div v-if="getShow" style="position: relative;">
		<div class="register-title">欢迎注册GpuMall</div>

		<div class="invite-info" v-show="getQueryString('user')">
			<InfoCircleFilled style="color:#1890FF;margin-right: 8px;" />
			<span>您的好友邀请您注册GpuMall</span>
		</div>

		<div class="register-type">
			<div class="activeType">注册</div>
		</div>
		<a-form loading :model="state.registerState" name="normal_register" class="register-form"
			@finishFailed="onFinishFailed">
			<a-form-item name="phone" :rules="[{ required: true, message: '请输入手机号!' }]">
				<a-input v-model:value="state.registerState.phone" allowClear autocomplete="off" size="large"
					placeholder="手机号">
					<template #prefix>
						<svg-icon name="icon_account_a" style="width: 12px;height: 12px;" />
					</template>
				</a-input>
			</a-form-item>

			<a-form-item name="password" :rules="[{ required: true, validator: validPwd, trigger: 'blur', }]">
				<a-input-password v-model:value="state.registerState.password" autocomplete="off"
					placeholder="请输入6-18位包含大小写字母和数字的密码" size="large">
					<template #prefix>
						<svg-icon name="icon_lock" style="width: 12px;height: 12px;" />
					</template>
				</a-input-password>
			</a-form-item>
			<a-form-item name="code" :rules="[{ required: true, message: '请输入验证码!' }]">
				<div class="form-item-code">
					<a-input v-model:value="state.registerState.code" allowClear autocomplete="off" size="large"
						placeholder="验证码">
						<template #prefix>
							<svg-icon name="icon_verify" style="width: 12px;height: 12px;" />
						</template>
					</a-input>
					<a-button type="link" :disabled="count != 0" class="get-code-btn" @click="sendCode()">{{ count > 0 ?
						count : '发送验证码' }} </a-button>
				</div>
			</a-form-item>
			<!-- geetest验证 -->
			<div id="captcha" style="height: 0;">
				<GeetestCaptcha :captcha-config="state.captchaConfig" />
			</div>
			<a-form-item class="mb-16">
				<a-button type="primary" style="width: 100%" :disabled="disabled" html-type="submit" size="large"
					@click="onFinish" class="register-form-button">
					注册
				</a-button>
			</a-form-item>

			<div class="login-opts">
				<div><span class="opt" @click="handleBackLogin">账号登录</span></div>
				<a-checkbox v-model:checked="checked" style="margin-right: 6px;display: flex;align-items: stretch;"><span style="font-size: 0.12rem;">我已阅读并同意<span class="opt"
							@click="goDocsAgreement">《用户服务协议》</span><span class="opt"
							@click="goDocsPrivacy">《隐私政策》</span></span></a-checkbox>

			</div>
		</a-form>
	</div>
</template>

<script setup>
import { reactive, computed, onMounted, ref } from 'vue'
import { useLoginState } from '@/hooks/sys/useLogin.js'
import { authRegister, authGetCode } from 'api/modules/api.auth'
import { useCountDown } from "@/hooks/sys/useCountDown.js";
import { isvalidPhone } from '@/libs/util.valid.js'
import { XsyMessage } from '@/libs/util.toast'
import GeetestCaptcha from "./GeetestCaptcha.vue";
import { getQueryString } from '@/libs/util.common'
import {
	InfoCircleFilled
} from '@ant-design/icons-vue';


const validPwd = async (_rule, value) => {
	const reg = /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{6,18}$/
	if (!value) {
		return Promise.reject('请输入密码');
	} else if (!reg.test(value)) {
		return Promise.reject('请输入6-18位包含大小写字母和数字的密码');
	} else {
		return Promise.resolve();
	}
};

// 倒计时
const { count, countDown } = useCountDown();

const { handleBackLogin, getLoginState } = useLoginState()

const getShow = computed(() => {
	return getLoginState.value === 'register'
})

const state = reactive({
	registerState: {
		phone: '',
		password: '',
		code: ''
	},
	captchaConfig: {
		config: {
			captchaId: "e0ff0f201c666d314840dfd88a2316f8",
			language: "zho",
			product: "bind",
		},
		handler: captchaHandler,
	},
})


const checked = ref(false)
const onFinish = () => {
	if (!checked.value) {
		XsyMessage.warning("请勾选协议")
		return
	}

	const params = {
		...state.registerState,
		invitedUserId: getQueryString('invitedUserId'),
		source: getQueryString('source')
	}

	authRegister(params).then(res => {
		(res.code == 0) && XsyMessage.success('注册成功')
		handleBackLogin()
	})
}

const onFinishFailed = errorInfo => {

}

const disabled = computed(() => {
	return !(state.registerState.phone && state.registerState.password)
})

// 点击发送验证码
function sendCode() {
	if (isvalidPhone(state.registerState.phone)) {
		if (window.captchaObj) {
			window.captchaObj.showCaptcha();
		} else {
			alert("请等待验证初始化完成");
			return false;
		}
	} else {
		XsyMessage.warning('请输入正确手机号');
	}
}

// 调用发送验证码接口
const GeetestResult = ref()
const getCode = () => {
	const params = {
		scene: 'register',
		account: state.registerState.phone,
		type: 'phone',
		...GeetestResult.value
	}

	authGetCode(params).then(res => {
		(res.code == 0) && XsyMessage.success('发送成功')
	})
};

function captchaHandler(captchaObj) {
	window.captchaObj = captchaObj;
	captchaObj
		.appendTo("#captcha")
		.onReady(function () {

		})
		.onNextReady(function () {

		})
		.onBoxShow(function () {

		})
		.onError(function (e) {

		})
		.onSuccess(function () {
			if (state.captchaConfig.config.product === "bind") {
				validate();
			}
		});
}

function validate() {
	var result = window.captchaObj.getValidate();
	GeetestResult.value = result;
	if (!result) {
		alert("请先完成验证！");
		return;
	}

	countDown(60, getCode)
}

// 打开隐私协议
function goDocsAgreement() {
	window.open(window.location.origin + '/docs/help_document/user_agreement/agreement', '_blank')
}

// 打开隐私协议
function goDocsPrivacy() {
	window.open(window.location.origin + '/docs/help_document/user_agreement/privacy', '_blank')
}

onMounted(() => {
	let html = document.documentElement;
	html.style.fontSize = 100 * (html.clientWidth / 1440) + "px";
	// 监听 window 的 resize 事件．在浏览器窗口变化时再设置下区域高度．
	window.onresize = () => {
		let html = document.documentElement;
		html.style.fontSize = 100 * (html.clientWidth / 1440) + "px";
	};
})

</script>

<style lang="scss" scoped>
.register-title {
	margin-bottom: 0.54rem;
	color: #222;
	font-family: PingFang SC;
	font-size: 0.32rem;
	font-style: normal;
	font-weight: 600;
	line-height: normal;
}

.invite-info {
	position: absolute;
	left: 0;
	top: 0.6rem;
	border-radius: 0.2rem;
	background: #A4C3EE;
	width: 3.4rem;
	height: 0.32rem;
	line-height: 0.32rem;
	padding: 0 0.14rem;
	font-size: 0.14rem;
	color: #223354;
	font-style: normal;
	font-weight: 400;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.register-type {
	display: flex;
	margin-bottom: 0.24rem;

	.activeType {
		color: #07F;
		font-family: PingFang SC;
		font-size: 0.16rem;
		font-style: normal;
		font-weight: 500;
		line-height: normal;
		margin-right: 0.24rem;
		cursor: pointer;
	}

	.activeType::after {
		height: 2px;
		content: '';
		background: #07F;
		display: block;
		margin-top: 4px;
	}
}

.register-form {
	overflow: hidden;

	.login-opts {
		display: flex;
		justify-content: space-between;
		align-items: center;
		color: #333;
		font-family: PingFang SC;
		font-size: 0.12rem;
		font-style: normal;
		font-weight: 500;
		line-height: normal;

		.opt {
			color: #07F;
		}
	}

	.ant-input-affix-wrapper {
		border-radius: 8px;
	}

}

.form-item-code {
	position: relative;
	border-radius: 6px;

	.get-code-btn {
		position: absolute;
		right: 0;
		height: 100%;
		border-radius: 0px 4px 4px 0px;
		border: none;
		background: #F2F8FF;
		z-index: 100;
		box-sizing: border-box;
	}
}
</style>
